package com.xinzhidi.web.netty.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.xinzhidi.common.constant.AgreementConstants;
import com.xinzhidi.common.utils.DateUtils;
import com.xinzhidi.common.utils.bean.BeanUtils;
import com.xinzhidi.common.utils.spring.SpringUtils;
import com.xinzhidi.web.alarmSetting.service.AlarmSettingService;
import com.xinzhidi.web.bigscreen.domain.vo.EnergyDataListVo;
import com.xinzhidi.web.build.domain.BuildUnit;
import com.xinzhidi.web.build.domain.CBuild;
import com.xinzhidi.web.build.service.IBuildUnitService;
import com.xinzhidi.web.build.service.ICBuildService;
import com.xinzhidi.web.custommodel.service.CustomModelService;
import com.xinzhidi.web.dataset.domain.DataSet;
import com.xinzhidi.web.dataset.domain.dto.DataSetDto;
import com.xinzhidi.web.dataset.service.DataSetService;
import com.xinzhidi.web.equipment.domain.Equipment;
import com.xinzhidi.web.equipment.domain.vo.EquipmentInfoVo;
import com.xinzhidi.web.equipment.service.EquipmentService;
import com.xinzhidi.web.house.domain.Household;
import com.xinzhidi.web.house.service.IHouseholdService;
import com.xinzhidi.web.netty.entity.AgreementBuildValveHistory;
import com.xinzhidi.web.netty.entity.AgreementHeatHistory;
import com.xinzhidi.web.netty.entity.AgreementUnitValveHistory;
import com.xinzhidi.web.netty.entity.DeviceInstruction;
import com.xinzhidi.web.plot.domain.entity.CPlot;
import com.xinzhidi.web.plot.service.ICPlotService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 户用、单元热量协议-（实时数据）Service业务层处理
 *
 * @author cx
 * @date 2023-06-17
 */
@Service
@RequiredArgsConstructor
public class NettyService {

    private final AgreementHouseholdValveService householdValveService;

    private final AgreementUnitValveService unitValveService;

    private final AgreementHeatService heatService;

    private final DataSetService dataSetService;

    private final CustomModelService customModelService;

    private final IHouseholdService householdService;

    private final IBuildUnitService buildUnitService;

    private final EquipmentService equipmentService;

    private final ICBuildService cBuildService;

    private final AgreementSeahorseValveService seahorseValveService;

    private final AlarmSettingService alarmSettingService;

    private final DeviceInstructionService deviceInstructionService;

    private final AgreementUnitValveHistoryService unitValveHistoryService;

    private final AgreementBuildValveHistoryService buildValveHistoryService;

    private final AgreementHeatHistoryService heatHistoryService;

    private final ICBuildService buildService;

    private final NettyUpdateService nettyUpdateService;

    private final AgreementBuildValveService agreementBuildValveService;

    //    @Transactional(rollbackFor = Exception.class)
    public void analyticData(String message, Equipment equipment, DeviceInstruction deviceInstruction) {
        //map为解析解析后的数据
        Map<String, Object> map = new HashMap<>();
        switch (equipment.getProtocolType()) {
            case AgreementConstants.AgreementType.HOUSEHOLD_VALVE:
                //户用阀门协议
                map = householdValveService.receiveHouseholdValve(message, deviceInstruction);
                break;
            case AgreementConstants.AgreementType.UNIT_VALVE:
                //单元阀门协议
                map = unitValveService.receiveUnitValve(message, deviceInstruction);
                break;
            case AgreementConstants.AgreementType.GREENHOUSE_COLLECTOR:
                //室温采集器
                break;
            case AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER:
                //户用热量表
                map = heatService.receiveHeat(message, deviceInstruction, AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER);
                break;
            case AgreementConstants.AgreementType.UNIT_HEAT_METER:
                //单元热量表-188-超声波楼栋热量表通讯协议
                map = heatService.receiveHeat(message, deviceInstruction, AgreementConstants.AgreementType.UNIT_HEAT_METER);
                break;
            case AgreementConstants.AgreementType.SEAHORSE_VALVE_METER:
                //海龙马调节阀协议
                map = seahorseValveService.seahorseProtocolAnalysis(message, deviceInstruction);
            case AgreementConstants.AgreementType.BUILD_VALVE:
                //楼栋阀门协议
                map = agreementBuildValveService.receiveBuildValve(message, deviceInstruction);
                break;
            case AgreementConstants.AgreementType.BUILD_HEAT_METER:
                //楼栋热量表
                map = heatService.receiveHeat(message, deviceInstruction, AgreementConstants.AgreementType.BUILD_HEAT_METER);
                break;
            default:
                break;
        }

        if (map.size() == 0) {
            return;
        }

        equipment.setStatus(1);
        equipmentService.updateById(equipment);
        System.out.println("-------更新设备【" + equipment.getAddress() + "】状态为在线!");

        deviceInstruction.setJsonData(JSON.toJSONString(map));

        deviceInstruction.setStatus(AgreementConstants.InstructSendingState.RETURN_TO_NORMAL);
        deviceInstructionService.updateById(deviceInstruction);
        System.out.println("-------更新指令【" + deviceInstruction.getId() + "】!");

        //如果是业务标识为1的数据，表示没有平台上的业务，不做任何操作
        if (deviceInstruction.getBusinessFlag().equals("1")) {
            return;
        }

        //更新维度的平均值。例：如果目前是消息是单元热量表的信息，那么首先更新单元表的供水温度等信息，然后判断是否有楼栋的设备
        //如果有楼栋的设备，则不做操作。如果没有楼栋的设备，则更新楼栋的供水温度等信息。然后再判断小区。以此类推
        //如果不是室温采集器的数据，才需要更新维度的平均值

        if (!equipment.getProtocolType().equals(AgreementConstants.AgreementType.GREENHOUSE_COLLECTOR)) {
            this.updateDimensionIndex(equipment, map);
        }
        //告警设置-超限异常检测（即设备数据校验）
        this.fieldCheck(equipment, map);

        //告警设置-波动异常检测
        this.fluctuationException(equipment, map);

        //判断是否是异常数据
//        if (this.isException(equipment, deviceInstruction, equipment.getProtocolType(), dataSet, map)) {
//            return;
//        }

        //找到数据对应的设置（在初始设置或平衡调控里设置的参数）。如果没有设置，则不需要进行下面的操作
        DataSet dataSet = dataSetService.getDataSetByDeviceInstruction(deviceInstruction);
        if (dataSet == null || dataSet.getControlStrategy() == null) {
            return;
        }
        //首先判断回复的数据是否有需要自动调控的数据，目前初始设置里需要调控的指标有下面几个
        //1：流量  2：回水温度  3：室内温度  4：供回水平均温度  5：热量
        //以上指标的协议有：户用热量表、单元热量表、室温采集器
        if (this.isContain(deviceInstruction)) {
            //判断是手动抄表还是自动抄表，如果是手动抄表，则不再做其他操作，如果是自动抄表，则还要判断是否是自动调控
            //如果是自动调控，则还需要自动调控
            //1：判断是否是自动抄表
            Integer businessType = deviceInstruction.getBusinessType();
            //如果不是自动抄表，则不做其他操作
            if (!businessType.equals(AgreementConstants.InstructBusinessType.AUTO_METER_READ)) {
                return;
            }
            if (dataSet == null) {
                return;
            }
            //3：自动调控
            this.automaticRegulation(equipment, dataSet, map, deviceInstruction);
        }
    }


    /**
     * 自动调控
     *
     * @param equipment 设备信息
     * @param dataSet   数据设置
     * @param map       解析后的数据
     * @return
     */
    public void automaticRegulation(Equipment equipment, DataSet dataSet, Map<String, Object> map, DeviceInstruction deviceInstruction) {
        //协议类型 1：户用阀门协议 2：单元阀门协议 3：室温采集器协议 4：户用热量表协议 5：单元热量表协议  6：海龙马调节阀协议
        EquipmentInfoVo equipmentInfoVo = new EquipmentInfoVo();
        DataSetDto dto = new DataSetDto();
        List<EquipmentInfoVo> totalEquipmentList = Lists.newArrayList();
        List<Integer> modelIdList = customModelService.getModelIdsByEquipment(equipment);
        BeanUtils.copyProperties(equipment, equipmentInfoVo);
        BeanUtils.copyProperties(dataSet, dto);
        totalEquipmentList.add(equipmentInfoVo);
        dataSetService.createBuildMessage(totalEquipmentList, dto, modelIdList, map, deviceInstruction);
    }

    /**
     * 更新维度的平均值
     * 例：如果目前是消息是单元热量表的信息，那么首先更新单元表的供水温度等信息，然后判断是否有楼栋的设备
     * 如果有楼栋的设备，则不做操作。如果没有楼栋的设备，则更新楼栋的供水温度等信息。然后再判断小区。以此类推
     *
     * @param equipment 设备信息
     * @param map       解析后的数据
     * @return
     */
    private void updateDimensionIndex(Equipment equipment, Map<String, Object> map) {
        String equipmentLevel = equipment.getEquipmentLevel();

        //下述代码逻辑
        //然后看住户对应的上级单元是否有设备，如果有设备，则不更新单元表数据，如果没有设备，则更新单元表数据

        if (equipmentLevel.equals(AgreementConstants.DataType.HOUSEHOLD)) {
            //住户
            nettyUpdateService.updateHouseholdData(equipment, map);
        } else if (equipmentLevel.equals(AgreementConstants.DataType.BUILD_UNIT)) {
            //单元
            nettyUpdateService.updateUnitData(equipment, map);
//            this.updateBuildUnitData(equipment, waterSupplyTemperature, returnWaterTemperature, velocityFlow, thermalPower, currentHeatOrCold, totalFlow, valveOpen, 0);
        } else if (equipmentLevel.equals(AgreementConstants.DataType.BUILD)) {
            //楼栋
            nettyUpdateService.updateBuildData(equipment, map);
//            this.updateBuildData(equipment, waterSupplyTemperature, returnWaterTemperature, velocityFlow, thermalPower, currentHeatOrCold, totalFlow, valveOpen, 0);
        }

    }


    /**
     * 更新住户的数据
     *
     * @param equipment              设备信息
     * @param waterSupplyTemperature 供水温度
     * @param returnWaterTemperature 回水温度
     * @param velocityFlow           瞬时流量
     * @param thermalPower           瞬时热量
     * @param currentHeatOrCold      累计热量
     * @param totalFlow              累计流量
     * @param valveOpen              阀门开度
     */
    public void updateHouseholdData(Equipment equipment, BigDecimal waterSupplyTemperature, BigDecimal returnWaterTemperature,
                                    BigDecimal velocityFlow,
                                    BigDecimal thermalPower,
                                    BigDecimal currentHeatOrCold,
                                    BigDecimal totalFlow,
                                    Integer valveOpen) {
        //根据住户级别更新上级维度数据
        //更新本身的数据
        Household household = householdService.getById(equipment.getHouseholdId());
        UpdateWrapper<Household> householdUpdateWrapper = new UpdateWrapper<>();
        if (waterSupplyTemperature != null) {
            householdUpdateWrapper.set("water_supply_temperature", waterSupplyTemperature);
        }
        if (returnWaterTemperature != null) {
            householdUpdateWrapper.set("return_water_temperature", returnWaterTemperature);
        }
        if (valveOpen != null) {
            householdUpdateWrapper.set("valve_open", valveOpen);
        }

        householdUpdateWrapper
                .set(velocityFlow != null, "velocity_flow", velocityFlow)
                .set(thermalPower != null, "thermal_power", thermalPower)
                .set(currentHeatOrCold != null, "current_heat_or_cold", currentHeatOrCold)
                .set(totalFlow != null, "total_flow", totalFlow)
                .set(waterSupplyTemperature != null, "water_supply_temperature", waterSupplyTemperature)
                .set(returnWaterTemperature != null, "return_water_temperature", returnWaterTemperature)
                .set(valveOpen != null, "valve_open", valveOpen);
        if (equipment.getProtocolType().equals(AgreementConstants.AgreementType.HOUSEHOLD_VALVE) ||
                equipment.getProtocolType().equals(AgreementConstants.AgreementType.SEAHORSE_VALVE_METER)) {
            householdUpdateWrapper.set("valve_read_time", DateUtils.getNowDate());
        }
        if (equipment.getProtocolType().equals(AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER)) {
            householdUpdateWrapper.set("heat_read_time", DateUtils.getNowDate());
        }
        householdUpdateWrapper.eq("id", household.getId());
        householdService.update(householdUpdateWrapper);
        //获取平均数。目前的住户，则计算住户的平均值
        if (this.updateSuperiorsData(equipment)) {
            this.updateBuildUnitData(equipment, waterSupplyTemperature, returnWaterTemperature, velocityFlow, thermalPower, currentHeatOrCold, totalFlow, valveOpen, 1);
        }
    }


    /**
     * 更新单元的数据
     *
     * @param equipment              设备信息
     * @param waterSupplyTemperature 供水温度
     * @param returnWaterTemperature 回水温度
     * @param velocityFlow           瞬时流量
     * @param thermalPower           瞬时热量
     * @param currentHeatOrCold      累计热量
     * @param totalFlow              累计流量
     * @param valveOpen              阀门开度
     * @param type                   类型 1：下级传来的数据 2：本身的数据
     * @apiNote 关于type的解释：1表示下级传来的数据，2表示本身的数据  如果是下级传来的数据，则需要先判断自身有没有设备，如果有，则不做操作
     * 如果没有，则更新自身的数据。然后再判断上级有没有设备，如果有，则更新上级的数据，以此类推
     * 当type为1时，回水温度这些数据是下级传来的数据，单元是更新下级数据的平均数还是不做操作，要看单元有无设备，有设备则不做操作，没有设备则更新下级数据的平均数
     */
    private void updateBuildUnitData(Equipment equipment, BigDecimal waterSupplyTemperature, BigDecimal returnWaterTemperature,
                                     BigDecimal velocityFlow,
                                     BigDecimal thermalPower,
                                     BigDecimal currentHeatOrCold,
                                     BigDecimal totalFlow,
                                     Integer valveOpen, int type) {
//        BuildUnit buildUnit = buildUnitService.getById(equipment.getUnitId());
        String protocolType = equipment.getProtocolType();
        UpdateWrapper<BuildUnit> buildUnitUpdateWrapper = new UpdateWrapper<>();
        Date heatReadTime = null;
        Date valveReadTime = null;
        if (type == 1) {
            //更新单元表的数据
            if (protocolType.equals(AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER)) {
                //根据单元id获取所有住户表的实时热量数据平均数
                Map<String, String> avgHeatMap = heatService.getAvgByBuildUnitId(equipment.getUnitId());
                Map<String, String> totalMap = heatService.getTotalHeatByBuildUnitId(equipment.getUnitId());
                if (avgHeatMap == null) {
                    return;
                }
                currentHeatOrCold = totalMap == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(totalMap.get("currentHeatOrCold")));
                totalFlow = totalMap == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(totalMap.get("totalFlow")));
                heatReadTime = DateUtils.getNowDate();
                thermalPower = new BigDecimal(String.valueOf(avgHeatMap.get("thermalPower")));
                velocityFlow = new BigDecimal(String.valueOf(avgHeatMap.get("velocityFlow")));
                waterSupplyTemperature = new BigDecimal(String.valueOf(avgHeatMap.get("waterSupplyTemperature")));
                returnWaterTemperature = new BigDecimal(String.valueOf(avgHeatMap.get("returnWaterTemperature")));

                AgreementHeatHistory heatHistory = new AgreementHeatHistory();
                heatHistory.setDeviceInstructionId(0L);
                heatHistory.setDtuId(0L);
                heatHistory.setProtocolType(AgreementConstants.AgreementType.UNIT_HEAT_METER);
                heatHistory.setProtocolName(AgreementConstants.AgreementTypeName.UNIT_HEAT_METER);
                heatHistory.setInstructType("1");
                heatHistory.setInstructName("读 热量表数据");
                heatHistory.setPlotId(equipment.getLotId());
                heatHistory.setBuildId(equipment.getBuildId());
                heatHistory.setUnitId(equipment.getUnitId());
                heatHistory.setPrefix("0");
                heatHistory.setStartChar("0");
                heatHistory.setDeviceType("20");
                heatHistory.setControlCode("0");
                heatHistory.setLengthField("0");
                heatHistory.setDataFieldMark("0");
                heatHistory.setDataFieldSerialNumber("0");
                heatHistory.setEndMark("0");
                heatHistory.setInstructionSet("0");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("totalFlow", totalFlow);
                jsonObject.put("currentHeatOrCold", currentHeatOrCold);
                jsonObject.put("thermalPower", thermalPower);
                jsonObject.put("velocityFlow", velocityFlow);
                jsonObject.put("returnWaterTemperature", returnWaterTemperature);
                jsonObject.put("waterSupplyTemperature", waterSupplyTemperature);

                heatHistory.setJsonData(jsonObject.toJSONString());
                heatHistoryService.save(heatHistory);
            } else {
                //根据单元id获取所有住户表的实时热量数据平均数
                EnergyDataListVo avgValveMap = heatService.getAvgValveByBuildUnitId(equipment.getUnitId());
                if (avgValveMap == null) {
                    return;
                }
                valveReadTime = DateUtils.getNowDate();
                valveOpen = avgValveMap.getValveOpen();


                buildUnitUpdateWrapper.set("valve_read_time", DateUtils.getNowDate());
                AgreementUnitValveHistory agreementUnitValveHistory = new AgreementUnitValveHistory();
                agreementUnitValveHistory.setDeviceInstructionId(0L);
                agreementUnitValveHistory.setDtuId(0L);
                agreementUnitValveHistory.setProtocolName(AgreementConstants.AgreementTypeName.UNIT_VALVE);
                agreementUnitValveHistory.setInstructType("1");
                agreementUnitValveHistory.setInstructName("读系统信息");
                agreementUnitValveHistory.setPlotId(equipment.getLotId());
                agreementUnitValveHistory.setBuildId(equipment.getBuildId());
                agreementUnitValveHistory.setUnitId(equipment.getUnitId());
                agreementUnitValveHistory.setPrefix("0");
                agreementUnitValveHistory.setStartChar("0");
                agreementUnitValveHistory.setDeviceType("40");
                agreementUnitValveHistory.setControlCode("0");
                agreementUnitValveHistory.setLengthField("0");
                agreementUnitValveHistory.setDataFieldMark("0");
                agreementUnitValveHistory.setDataFieldSerialNumber("0");
                agreementUnitValveHistory.setEndMark("0");
                agreementUnitValveHistory.setInstructionSet("0");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("readOpenValue", valveOpen);
                agreementUnitValveHistory.setJsonData(jsonObject.toJSONString());
                unitValveHistoryService.save(agreementUnitValveHistory);
            }
        }
        buildUnitUpdateWrapper.set("thermal_power", thermalPower)
                .set("velocity_flow", velocityFlow)
                .set("total_flow", totalFlow)
                .set("current_heat_or_cold", currentHeatOrCold)
                .set("water_supply_temperature", waterSupplyTemperature)
                .set("return_water_temperature", returnWaterTemperature)
                .set("valve_open", valveOpen);
        //说明是阀门
        if (equipment.getEquipmentType().equals("1")) {
            buildUnitUpdateWrapper.set("valve_read_time", DateUtils.getNowDate());
        } else {
            buildUnitUpdateWrapper.set("heat_read_time", DateUtils.getNowDate());
        }
        buildUnitUpdateWrapper.eq("id", equipment.getUnitId());
        buildUnitService.update(buildUnitUpdateWrapper);
        //更新楼栋的数据
        if (this.updateSuperiorsData(equipment)) {
            this.updateBuildData(equipment, waterSupplyTemperature, returnWaterTemperature, velocityFlow, thermalPower, currentHeatOrCold, totalFlow, valveOpen, 1);
        }
    }

    /**
     * 更新楼栋的数据
     *
     * @param equipment              设备信息
     * @param waterSupplyTemperature 供水温度
     * @param returnWaterTemperature 回水温度
     * @param velocityFlow           瞬时流量
     * @param thermalPower           瞬时热量
     * @param currentHeatOrCold      累计热量
     * @param totalFlow              累计流量
     * @param valveOpen              阀门开度
     * @param type                   类型 1：下级传来的数据 2：本身的数据
     * @apiNote 关于type的解释：1表示下级传来的数据，2表示本身的数据  如果是下级传来的数据，则需要先判断自身有没有设备，如果有，则不做操作
     * 如果没有，则更新自身的数据。然后再判断上级有没有设备，如果有，则更新上级的数据，以此类推
     * 当type为1时，回水温度这些数据是下级传来的数据，单元是更新下级数据的平均数还是不做操作，要看单元有无设备，有设备则不做操作，没有设备则更新下级数据的平均数
     */
    private void updateBuildData(Equipment equipment, BigDecimal waterSupplyTemperature, BigDecimal returnWaterTemperature,
                                 BigDecimal velocityFlow,
                                 BigDecimal thermalPower,
                                 BigDecimal currentHeatOrCold,
                                 BigDecimal totalFlow,
                                 Integer valveOpen, int type) {

        UpdateWrapper<CBuild> buildUpdateWrapper = new UpdateWrapper<>();
        Date heatReadTime = null;
        Date valveReadTime = null;
        String protocolType = equipment.getProtocolType();
        if (type == 1) {
            if (protocolType.equals(AgreementConstants.AgreementType.UNIT_HEAT_METER)) {
                //根据楼栋id获取所有单元表的实时热量数据平均数
                Map<String, String> avgHeatMap = heatService.getAvgByBuildId(equipment.getBuildId());
                Map<String, String> totalMap = heatService.getTotalHeatByBuildId(equipment.getBuildId());
                if (avgHeatMap == null) {
                    return;
                }
                currentHeatOrCold = totalMap == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(totalMap.get("currentHeatOrCold")));
                totalFlow = totalMap == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(totalMap.get("totalFlow")));
                heatReadTime = DateUtils.getNowDate();
                thermalPower = new BigDecimal(String.valueOf(avgHeatMap.get("thermalPower")));
                velocityFlow = new BigDecimal(String.valueOf(avgHeatMap.get("velocityFlow")));
                waterSupplyTemperature = new BigDecimal(String.valueOf(avgHeatMap.get("waterSupplyTemperature")));
                returnWaterTemperature = new BigDecimal(String.valueOf(avgHeatMap.get("returnWaterTemperature")));
                buildUpdateWrapper.set("thermal_power", thermalPower)
                        .set("velocity_flow", velocityFlow)
                        .set("total_flow", totalFlow)
                        .set("current_heat_or_cold", currentHeatOrCold)
                        .set("water_supply_temperature", waterSupplyTemperature)
                        .set("return_water_temperature", returnWaterTemperature)
                        .set("heat_read_time", heatReadTime);

                AgreementHeatHistory heatHistory = new AgreementHeatHistory();
                heatHistory.setDeviceInstructionId(0L);
                heatHistory.setDtuId(0L);
                heatHistory.setProtocolType(AgreementConstants.AgreementType.BUILD_HEAT_METER);
                heatHistory.setProtocolName(AgreementConstants.AgreementTypeName.BUILD_HEAT_METER);
                heatHistory.setInstructType("1");
                heatHistory.setInstructName("读 热量表数据");
                heatHistory.setPlotId(equipment.getLotId());
                heatHistory.setBuildId(equipment.getBuildId());
                heatHistory.setPrefix("0");
                heatHistory.setStartChar("0");
                heatHistory.setDeviceType("20");
                heatHistory.setControlCode("0");
                heatHistory.setLengthField("0");
                heatHistory.setDataFieldMark("0");
                heatHistory.setDataFieldSerialNumber("0");
                heatHistory.setEndMark("0");
                heatHistory.setInstructionSet("0");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("totalFlow", totalFlow);
                jsonObject.put("currentHeatOrCold", currentHeatOrCold);
                jsonObject.put("thermalPower", thermalPower);
                jsonObject.put("velocityFlow", velocityFlow);
                jsonObject.put("returnWaterTemperature", returnWaterTemperature);
                jsonObject.put("waterSupplyTemperature", waterSupplyTemperature);

                heatHistory.setJsonData(jsonObject.toJSONString());
                heatHistoryService.save(heatHistory);
            } else {
                EnergyDataListVo avgValveMap = heatService.getAvgValveByBuildId(equipment.getBuildId());
                if (avgValveMap == null) {
                    return;
                }
                valveReadTime = DateUtils.getNowDate();
                valveOpen = avgValveMap.getValveOpen();


                buildUpdateWrapper.set("valve_read_time", valveReadTime);
                AgreementBuildValveHistory buildValveHistory = new AgreementBuildValveHistory();
                buildValveHistory.setDeviceInstructionId(0L);
                buildValveHistory.setDtuId(0L);
                buildValveHistory.setProtocolName(AgreementConstants.AgreementTypeName.BUILD_VALVE);
                buildValveHistory.setInstructType("1");
                buildValveHistory.setInstructName("读系统信息");
                buildValveHistory.setPlotId(equipment.getLotId());
                buildValveHistory.setBuildId(equipment.getBuildId());
                buildValveHistory.setPrefix("0");
                buildValveHistory.setStartChar("0");
                buildValveHistory.setDeviceType("40");
                buildValveHistory.setControlCode("0");
                buildValveHistory.setLengthField("0");
                buildValveHistory.setDataFieldMark("0");
                buildValveHistory.setDataFieldSerialNumber("0");
                buildValveHistory.setEndMark("0");
                buildValveHistory.setInstructionSet("0");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("readOpenValue", valveOpen);
                buildValveHistory.setJsonData(jsonObject.toJSONString());
                buildValveHistoryService.save(buildValveHistory);
            }
        } else {
            //更新小区的数据
            //获取小区id
            this.updatePlotData(equipment, waterSupplyTemperature, returnWaterTemperature, velocityFlow, thermalPower, currentHeatOrCold, totalFlow, valveOpen);
        }
        buildUpdateWrapper.set("thermal_power", thermalPower)
                .set("velocity_flow", velocityFlow)
                .set("total_flow", totalFlow)
                .set("current_heat_or_cold", currentHeatOrCold)
                .set("water_supply_temperature", waterSupplyTemperature)
                .set("return_water_temperature", returnWaterTemperature);
        buildUpdateWrapper.set("valve_open", valveOpen);
        //说明是阀门
        if (equipment.getEquipmentType().equals("1")) {
            buildUpdateWrapper.set("valve_read_time", DateUtils.getNowDate());
        } else {
            buildUpdateWrapper.set("heat_read_time", DateUtils.getNowDate());
        }


        buildUpdateWrapper.eq("id", equipment.getBuildId());
        buildService.update(buildUpdateWrapper);
    }

    /**
     * 更新小区的数据
     *
     * @param waterSupplyTemperature 供水温度
     * @param returnWaterTemperature 回水温度
     * @param velocityFlow           瞬时流量
     * @param thermalPower           瞬时热量
     * @param currentHeatOrCold      累计热量
     * @param totalFlow              累计流量
     * @param valveOpen              阀门开度
     */
    private void updatePlotData(Equipment equipment, BigDecimal waterSupplyTemperature, BigDecimal returnWaterTemperature,
                                BigDecimal velocityFlow,
                                BigDecimal thermalPower,
                                BigDecimal currentHeatOrCold,
                                BigDecimal totalFlow,
                                Integer valveOpen) {
        ICPlotService plotService = SpringUtils.getBean(ICPlotService.class);
        ICBuildService buildService = SpringUtils.getBean(ICBuildService.class);
        LambdaQueryWrapper<CBuild> buildWrapper = Wrappers.lambdaQuery();
        buildWrapper.eq(CBuild::getPlotId, equipment.getLotId())
                .eq(CBuild::getDelFlag, AgreementConstants.DEL_FLAG_NO);
        if (valveOpen != null) {
            buildWrapper.isNotNull(CBuild::getValveReadTime);
        } else {
            buildWrapper.isNotNull(CBuild::getHeatReadTime);
        }
        List<CBuild> buildList = buildService.list(buildWrapper);
        if (CollectionUtils.isNotEmpty(buildList)) {
            //获取瞬时流量的平均值
            velocityFlow = buildList.stream().filter(build -> build.getVelocityFlow() != null)
                    .map(CBuild::getVelocityFlow)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(new BigDecimal(buildList.size()), 2, BigDecimal.ROUND_HALF_UP);
            //获取瞬时热量的平均值
            thermalPower = buildList.stream().filter(build -> build.getThermalPower() != null)
                    .map(CBuild::getThermalPower)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(new BigDecimal(buildList.size()), 2, BigDecimal.ROUND_HALF_UP);
            //获取累计热量的平均值
            currentHeatOrCold = buildList.stream().filter(build -> build.getCurrentHeatOrCold() != null)
                    .map(CBuild::getCurrentHeatOrCold)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(new BigDecimal(buildList.size()), 2, BigDecimal.ROUND_HALF_UP);
            //获取累计流量的平均值
            totalFlow = buildList.stream().filter(build -> build.getTotalFlow() != null)
                    .map(CBuild::getTotalFlow)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(new BigDecimal(buildList.size()), 2, BigDecimal.ROUND_HALF_UP);

            //获取供水温度的平均值
            waterSupplyTemperature = buildList.stream().filter(build -> build.getWaterSupplyTemperature() != null)
                    .map(CBuild::getWaterSupplyTemperature)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(new BigDecimal(buildList.size()), 2, BigDecimal.ROUND_HALF_UP);
            //获取回水温度的平均值
            returnWaterTemperature = buildList.stream().filter(build -> build.getReturnWaterTemperature() != null)
                    .map(CBuild::getReturnWaterTemperature)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(new BigDecimal(buildList.size()), 2, BigDecimal.ROUND_HALF_UP);
            //获取阀门开度的平均值
            valveOpen = buildList.stream().filter(build -> build.getValveOpen() != null)
                    .map(CBuild::getValveOpen).reduce(0, Integer::sum) / buildList.size();
            UpdateWrapper<CPlot> plotUpdateWrapper = new UpdateWrapper<>();
            plotUpdateWrapper.set("thermal_power", thermalPower)
                    .set("velocity_flow", velocityFlow)
                    .set("total_flow", totalFlow)
                    .set("current_heat_or_cold", currentHeatOrCold)
                    .set("water_supply_temperature", waterSupplyTemperature)
                    .set("return_water_temperature", returnWaterTemperature)
                    .set("valve_open", valveOpen);
            if (valveOpen != null) {
                plotUpdateWrapper.set("valve_read_time", DateUtils.getNowDate());
            }
            if (velocityFlow != null) {
                plotUpdateWrapper.set("heat_read_time", DateUtils.getNowDate());
            }
            plotUpdateWrapper.eq("id", equipment.getLotId());
            plotService.update(plotUpdateWrapper);
        }
    }


    //告警设置-超限异常监测（即设备数据校验）
    public void fieldCheck(Equipment equipment, Map<String, Object> map) {
        alarmSettingService.fieldCheck(equipment, map);
    }

    //告警设置-波动异常监测
    public void fluctuationException(Equipment equipment, Map<String, Object> map) {
        alarmSettingService.fluctuationException(equipment, map);
    }

    /**
     * 判断回复的数据是否是异常数据或不在目标范围内的数据
     * 如果是异常数据，则保存至设备告警表
     * 如果不在目标范围内，则自动调控
     *
     * @param equipment         设备
     * @param deviceInstruction 下发的指令
     * @param protocolType      协议类型 1：户用阀门协议 2：单元阀门协议 3：室温采集器协议 4：户用热量表协议 5：单元热量表协议
     * @param dataSet           数据对应的设置
     * @param map               解析后的数据
     * @return
     */
//    public boolean isException(Equipment equipment, DeviceInstruction deviceInstruction, String
//            protocolType, DataSet dataSet, Map<String, Object> map) {
//        //默认为true（异常数据）
//        boolean flag = true;
//        EquipmentAlarmService equipmentAlarmService = SpringUtils.getBean(EquipmentAlarmService.class);
//        //调控策略
//        String controlStrategy = dataSet.getControlStrategy();
//        AlarmSetting alarmSetting = null;
//        EquipmentAlarm equipmentAlarm = new EquipmentAlarm();
//        equipmentAlarm.setPlotId(deviceInstruction.getPlotId());
//        equipmentAlarm.setBuildId(deviceInstruction.getBuildId());
//        equipmentAlarm.setUnitId(deviceInstruction.getUnitId());
//        equipmentAlarm.setHouseholdId(deviceInstruction.getHouseholdId());
//        equipmentAlarm.setEquipmentId(equipment.getId());
//        if (protocolType.equals(AgreementConstants.AgreementType.GREENHOUSE_COLLECTOR)) {
//            //室温采集器
//            alarmSetting = this.checkException(equipment, equipmentAlarm, AgreementConstants.AgreementType.GREENHOUSE_COLLECTOR, controlStrategy, dataSet, map);
//        } else if (protocolType.equals(AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER)) {
//            //户用热量表
//            //判断是否是异常数据
//            alarmSetting = this.checkException(equipment, equipmentAlarm, AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER, controlStrategy, dataSet, map);
//
//        } else if (protocolType.equals(AgreementConstants.AgreementType.UNIT_HEAT_METER)) {
//            //单元热量表
//            alarmSetting = this.checkException(equipment, equipmentAlarm, AgreementConstants.AgreementType.UNIT_HEAT_METER, controlStrategy, dataSet, map);
//        }
//        if (alarmSetting != null) {
//            //2：保存至设备告警表
//            equipmentAlarm.setAlarmSettingId(alarmSetting.getId());
//            equipmentAlarm.setRemark(alarmSetting.getRemark());
////            equipmentAlarm.setExceptionType(Integer.valueOf(dataSet.getControlStrategy()));
////            equipmentAlarm.setExceptionName(this.getExceptionName(equipmentAlarm.getExceptionType()));
//            equipmentAlarmService.save(equipmentAlarm);
//        } else {
//            flag = false;
//        }
//        return flag;
//    }

    /**
     * 获取异常名称
     *
     * @param type 调控策略
     * @return
     */
    private String getExceptionName(Integer type) {
        String name = "";
        if (type == 1) {
            return AgreementConstants.ExceptionName.RETURN_WATER_TEMPERATURE;
        }
        if (type == 2) {
            return AgreementConstants.ExceptionName.ROOM_TEMPERATURE;
        }
        if (type == 3) {
            return AgreementConstants.ExceptionName.SUPPLY_AND_RETURN_WATER;
        }
        if (type == 4) {
            return AgreementConstants.ExceptionName.FLOW_RATE;
        }
        if (type == 5) {
            return AgreementConstants.ExceptionName.HEAT;
        }
        return name;
    }

    /**
     * 判断是否是异常数据
     *
     * @param equipment       设备
     * @param equipmentAlarm  设备告警
     * @param type            协议类型  1：户用阀门协议 2：单元阀门协议 3：室温采集器  4：户用热量表 ：5 单元热量表  (改方里用于查找alarm_setting表数据的条件：查询equipment_type字段)
     * @param controlStrategy 调控策略
     * @param dataSet         数据对应的设置
     * @param map             解析后的数据
     * @return
     */
//    public AlarmSetting checkException(Equipment equipment, EquipmentAlarm equipmentAlarm, String type, String controlStrategy, DataSet
//            dataSet, Map<String, Object> map) {
//        LambdaQueryWrapper<AlarmSetting> queryWrapper = Wrappers.lambdaQuery();
//        AlarmSetting alarmSetting = null;
//        //是否有异常   默认false：没有
//        boolean exceptionFlag = false;
//
//        //TODO 后期删除
//        Long userId;
//        try {
//            LoginUser loginUser = SecurityUtils.getLoginUser();
//            userId = loginUser.getUserId();
//        } catch (Exception e) {
//            userId = 1L;
//        }
////        Long userId = SecurityUtils.getLoginUser().getUserId();
//
//        BigDecimal value = BigDecimal.ZERO;
//
//        String message = "";
//        JSONObject jsonObject = new JSONObject();
//        if (controlStrategy.equals(AgreementConstants.ControlTactics.RETURN_WATER_TEMPERATURE)) {
//            //设备上报的回水温度
//            BigDecimal returnWaterTemperature = new BigDecimal(map.get("returnWaterTemperature").toString());
//            //判断是否是异常数据
//            //回水温度异常最大值
//            BigDecimal returnWaterMaxValue = dataSet.getReturnWaterMaxValue();
//            //回水温度异常最小值
//            BigDecimal returnWaterMinValue = dataSet.getReturnWaterMinValue();
//            if (returnWaterTemperature.compareTo(returnWaterMaxValue) == 1 || returnWaterTemperature.compareTo(returnWaterMinValue) == -1) {
//                //回水温度异常
//                queryWrapper
//                        .eq(AlarmSetting::getAlarmType, AgreementConstants.ExceptionType.TRANSFINITE_EXCEPTION)
//                        .eq(AlarmSetting::getIndexType, 1)
//                        .eq(AlarmSetting::getDelFlag, AgreementConstants.DEL_FLAG_NO);
////                equipmentAlarm.setExceptionType(AgreementConstants.ExceptionType.RETURN_WATER_TEMPERATURE);
////                equipmentAlarm.setExceptionName(AgreementConstants.ExceptionName.RETURN_WATER_TEMPERATURE);
//                message = "设备【" + equipment.getEquipmentName() + "】" + "回水温度异常";
//                exceptionFlag = true;
//            }
//            value = returnWaterTemperature;
//        } else if (controlStrategy.equals(AgreementConstants.ControlTactics.AVERAGE_AND_RETURN_WATER)) {
//            //供回水平均温度
//
//            //设备上报的供水温度
//            BigDecimal waterSupplyTemperature = new BigDecimal(map.get("waterSupplyTemperature").toString());
//
//            //设备上报的回水温度
//            BigDecimal returnWaterTemperature = new BigDecimal(map.get("returnWaterTemperature").toString());
//            //获取供回水平均温度
//            BigDecimal averageAndReturnWater = (waterSupplyTemperature.add(returnWaterTemperature)).divide(new BigDecimal(2), 2, BigDecimal.ROUND_HALF_UP);
//            //判断是否是异常数据
//            //供回水平均温度异常最大值
//            BigDecimal farReturnMaxValue = dataSet.getFarReturnMaxValue();
//            //供回水平均温度异常最小值
//            BigDecimal farReturnMinValue = dataSet.getFarReturnMinValue();
//
//            if (averageAndReturnWater.compareTo(farReturnMaxValue) == 1 || averageAndReturnWater.compareTo(farReturnMinValue) == -1) {
//                //供回水平均温度异常
//                queryWrapper
//                        .eq(AlarmSetting::getAlarmType, AgreementConstants.ExceptionType.TRANSFINITE_EXCEPTION)
//                        .eq(AlarmSetting::getIndexType, 3)
//                        .eq(AlarmSetting::getDelFlag, AgreementConstants.DEL_FLAG_NO);
////                equipmentAlarm.setExceptionType(AgreementConstants.ExceptionType.SUPPLY_AND_RETURN_WATER);
////                equipmentAlarm.setExceptionName(AgreementConstants.ExceptionName.SUPPLY_AND_RETURN_WATER);
//                message = "设备【" + equipment.getEquipmentName() + "】" + "供回水平均温度异常";
//                exceptionFlag = true;
//            }
//            value = waterSupplyTemperature;
//        } else if (controlStrategy.equals(AgreementConstants.ControlTactics.FLOW_RATE)) {
//            //设备上报的流量
//            BigDecimal velocityFlow = new BigDecimal(map.get("velocityFlow").toString());
//            //判断是否是异常数据
//            BigDecimal velocityFlowMaxValue = dataSet.getVelocityFlowMaxValue();
//            BigDecimal velocityFlowMinValue = dataSet.getVelocityFlowMinValue();
//
//            if (velocityFlow.compareTo(velocityFlowMaxValue) == 1 || velocityFlow.compareTo(velocityFlowMinValue) == -1) {
//                //流量异常
//                queryWrapper
//                        .eq(AlarmSetting::getAlarmType, AgreementConstants.ExceptionType.TRANSFINITE_EXCEPTION)
//                        .eq(AlarmSetting::getIndexType, 4)
//                        .eq(AlarmSetting::getDelFlag, AgreementConstants.DEL_FLAG_NO);
//                message = "设备【" + equipment.getEquipmentName() + "】" + "流量异常";
//                exceptionFlag = true;
//            }
//            value = velocityFlow;
//        } else if (controlStrategy.equals(AgreementConstants.ControlTactics.HEAT)) {
//            //设备上报的热量
//            BigDecimal currentHeatOrCold = new BigDecimal(map.get("currentHeatOrCold").toString());
//            //判断是否是异常数据
//            BigDecimal heatMaxValue = dataSet.getHeatMaxValue();
//            BigDecimal heatMinValue = dataSet.getHeatMinValue();
//
//            if (currentHeatOrCold.compareTo(heatMaxValue) == 1 || currentHeatOrCold.compareTo(heatMinValue) == -1) {
//                //热量异常
//                queryWrapper
//                        .eq(AlarmSetting::getAlarmType, AgreementConstants.ExceptionType.TRANSFINITE_EXCEPTION)
//                        .eq(AlarmSetting::getIndexType, 5)
//                        .eq(AlarmSetting::getDelFlag, AgreementConstants.DEL_FLAG_NO);
////                equipmentAlarm.setExceptionType(AgreementConstants.ExceptionType.HEAT);
////                equipmentAlarm.setExceptionName(AgreementConstants.ExceptionName.HEAT);
//                message = "设备【" + equipment.getEquipmentName() + "】" + "热量异常";
//                exceptionFlag = true;
//            }
//            value = currentHeatOrCold;
//
//        } else if (controlStrategy.equals(AgreementConstants.ControlTactics.ROOM_TEMPERATURE)) {
//            //设备上报的室内温度
//            BigDecimal roomTemperature = new BigDecimal(map.get("roomTemperature").toString());
//            //判断是否是异常数据
//            BigDecimal roomTemperatureMaxValue = dataSet.getTargetRoomMaxValue();
//            BigDecimal roomTemperatureMinValue = dataSet.getTargetRoomMinValue();
//
//            if (roomTemperature.compareTo(roomTemperatureMaxValue) == 1 || roomTemperature.compareTo(roomTemperatureMinValue) == -1) {
//                //室内温度异常
//                queryWrapper.eq(AlarmSetting::getIndexType, AgreementConstants.AgreementType.GREENHOUSE_COLLECTOR)
//                        .eq(AlarmSetting::getDelFlag, AgreementConstants.DEL_FLAG_NO);
////                equipmentAlarm.setExceptionType(AgreementConstants.ExceptionType.ROOM_TEMPERATURE);
////                equipmentAlarm.setExceptionName(AgreementConstants.ExceptionName.ROOM_TEMPERATURE);
//                message = "设备【" + equipment.getEquipmentName() + "】" + "室内温度异常";
//                exceptionFlag = true;
//            }
//            value = roomTemperature;
//        }
//        if(exceptionFlag){
//            alarmSetting = alarmSettingService.getOne(queryWrapper);
//            if (alarmSetting != null) {
//                alarmSetting.setRemark(message);
//                //发送消息推送
//                if (StringUtils.isNotBlank(message)) {
//                    //1表示数据上报异常
//                    jsonObject.put("type", 1);
//                    jsonObject.put("message", message);
//                    WebSocketUsers.sendMessageToUserByUserId(String.valueOf(userId), jsonObject.toString());
//                }
////                else {
////                    //判断是否在告知设置的波动范围内，不在，则产生波动异常
////                    BigDecimal maxValue = alarmSetting.getTargetValue().add(alarmSetting.getFluctuatingValue());
////                    BigDecimal minValue = alarmSetting.getTargetValue().subtract(alarmSetting.getFluctuatingValue());
////                    if (value.compareTo(maxValue) == 1 || value.compareTo(minValue) == -1) {
////                        //波动异常
////                        EquipmentAlarm alarm = new EquipmentAlarm();
////                        alarm.setPlotId(equipment.getLotId());
////                        alarm.setBuildId(equipment.getBuildId());
////                        alarm.setUnitId(equipment.getUnitId());
////                        alarm.setHouseholdId(equipment.getHouseholdId());
////                        alarm.setAlarmSettingId(alarmSetting.getId());
////                        alarm.setHideOrPush(Integer.parseInt(alarmSetting.getPushStatus()));
////                        equipmentAlarmService.save(alarm);
////                    } else {
////                        alarmSetting = null;
////                    }
////                }
//            }
//        }
//
//
//        return alarmSetting;
//    }

    /**
     * 判断下发的指令是否包含需要自动调控的指标数据，如：流量、回水温度等
     *
     * @return
     */
    public boolean isContain(DeviceInstruction deviceInstruction) {
        //默认不包含
        boolean flag = false;
        String protocolType = deviceInstruction.getProtocolType();
        if (protocolType.equals(AgreementConstants.AgreementType.GREENHOUSE_COLLECTOR) ||
                protocolType.equals(AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER) ||
                protocolType.equals(AgreementConstants.AgreementType.UNIT_HEAT_METER)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 根据设备判断是否更新他的上级维度数据
     *
     * @param equipment 设备
     * @return true：更新  false：不更新
     */
    public boolean updateSuperiorsData(Equipment equipment) {

        boolean flag = false;
        //获取该设备上级维度是否有设备，并且是否有未发送的指令
        String equipmentLevel = equipment.getEquipmentLevel();
        Integer num = 0;
        Long id;
        String protocolType = equipment.getProtocolType();
        LambdaQueryWrapper<Equipment> queryWrapper = Wrappers.lambdaQuery();
        List<Equipment> equipmentList;
        List<String> protocolTypeList = Lists.newArrayList();
        if (equipmentLevel.equals(AgreementConstants.DataType.HOUSEHOLD)) {
            id = equipment.getUnitId();
            queryWrapper.clear();
            queryWrapper.eq(Equipment::getUnitId, id)
                    .eq(Equipment::getEquipmentLevel, AgreementConstants.DataType.BUILD_UNIT)
                    .eq(Equipment::getDelFlag, AgreementConstants.DEL_FLAG_NO);
            //住户设备,获取单元id

            if (protocolType.equals(AgreementConstants.AgreementType.HOUSEHOLD_VALVE) ||
                    protocolType.equals(AgreementConstants.AgreementType.SEAHORSE_VALVE_METER)) {
                protocolTypeList.add(AgreementConstants.AgreementType.HOUSEHOLD_VALVE);
                protocolTypeList.add(AgreementConstants.AgreementType.SEAHORSE_VALVE_METER);

                //如果获取的数据是户用阀门或海龙马阀门，则判断他上级单元是否有单元阀门表，如果有，则判断是否有未发送的指令，如果没有，则更新
                queryWrapper.eq(Equipment::getProtocolType, AgreementConstants.AgreementType.UNIT_VALVE);
            } else if (protocolType.equals(AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER)) {
                protocolTypeList.add(AgreementConstants.AgreementType.HOUSEHOLD_HEAT_METER);
                queryWrapper.eq(Equipment::getProtocolType, AgreementConstants.AgreementType.UNIT_HEAT_METER);
            }
            equipmentList = equipmentService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(equipmentList)) {
                flag = false;
            } else {
                //获取该单元下所有设备是否还有未发送的指令
                num = equipmentService.getNoSendEquipmentNumber("e.unit_id", id, AgreementConstants.DataType.BUILD_UNIT, protocolTypeList);
                flag = num > 0 ? false : true;
            }
        } else if (equipmentLevel.equals(AgreementConstants.DataType.BUILD_UNIT)) {
            id = equipment.getBuildId();
            queryWrapper.clear();
            queryWrapper.eq(Equipment::getBuildId, id)
                    .eq(Equipment::getEquipmentLevel, AgreementConstants.DataType.BUILD)
                    .eq(Equipment::getDelFlag, AgreementConstants.DEL_FLAG_NO);
            //住户设备,获取单元id
            if (protocolType.equals(AgreementConstants.AgreementType.UNIT_VALVE)) {
                protocolTypeList.add(AgreementConstants.AgreementType.UNIT_VALVE);
                //如果获取的数据是单元阀门，则判断他上级楼栋是否有楼栋阀门表，如果有，则判断是否有未发送的指令，如果没有，则更新
                queryWrapper.eq(Equipment::getProtocolType, AgreementConstants.AgreementType.BUILD_VALVE);
            } else if (protocolType.equals(AgreementConstants.AgreementType.UNIT_HEAT_METER)) {
                protocolTypeList.add(AgreementConstants.AgreementType.UNIT_HEAT_METER);
                queryWrapper.eq(Equipment::getProtocolType, AgreementConstants.AgreementType.BUILD_HEAT_METER);
            }
            equipmentList = equipmentService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(equipmentList)) {
                flag = false;
            } else {
                //获取该单元下所有设备是否还有未发送的指令
                num = equipmentService.getNoSendEquipmentNumber("e.build_id", id, AgreementConstants.DataType.BUILD, protocolTypeList);
                flag = num > 0 ? false : true;
            }
        } else {
//            id = equipment.getLotId();
//            num = equipmentService.getNoSendEquipmentNumber("e.lot_id", id, AgreementConstants.DataType.PLOT);
//            flag = num > 0 ? false : true;
        }
        return flag;
    }
}
